from django.shortcuts import render

# Create your views here.
import hashlib
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from user.models import UserProfile
from user.views import make_token


class TokenView(View):
    def post(self,request):
        # add your code here
        #1 获取前端提供过来的json，从request.body中拿
        json_str = request.body
        #2将json串反序列化为对象，一般拿到是字典
        py_obj=json.loads(json_str)
        username=py_obj['username']
        password=py_obj['password']
        # 3 print一下用户名密码
        print(username,password)
        #4根据用户名get一下用户对象user,get时加try
        try:
            user=UserProfile.objects.get(
                username=username,
            )
        except Exception as e:
            print('the error is %s' % e)
            result = {'code': 20100, 'error': '用户名或密码错误'}
            return JsonResponse(result)
        # 5根据输入的password,计算hash值
        md5 = hashlib.md5()
        md5.update(password.encode())
        password_h = md5.hexdigest()
        # 与user.passsword比时，如果不相等，提示错误
        if password_h != user.password:
            result = {'code': 20101, 'error': '用户名或密码错误'}
            return JsonResponse(result)
        #6通过验证后，生成并返回tooken,参考注册的代码
        token = make_token(username)
        token = token.decode()
        return JsonResponse({'code': 200, 'username': username,
                             'data': {'token': token}})

